package com.example.leero.graduation.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.ant.liao.GifView;
import com.example.leero.graduation.API;
import com.example.leero.graduation.App;
import com.example.leero.graduation.R;
import com.example.leero.graduation.Util.LogUtil;
import com.example.leero.graduation.Util.StepDetector;
import com.example.leero.graduation.service.StepCounterService;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;

import okhttp3.Call;

public class RunActivity extends AppCompatActivity {

    private ImageButton back;
    private TextView tv_setting;
    private TextView tv_show_step;// 步数
    private TextView tv_timer;// 运行时间
    private TextView tv_distance;// 行程

    private Button btn_start;// 开始按钮
    private Button btn_stop;// 停止按钮

    private GifView gifView;

    private long timer = 0;// 运动时间
    private  long startTimer = 0;// 开始时间
    private  long tempTime = 0;
    private Double distance = 0.0;// 路程：米
    private int step_length = 0;  //步长
    private int total_step = 0;   //走的总步数

    private Thread thread;  //定义线程对象

    // 当创建一个新的Handler实例时, 它会绑定到当前线程和消息的队列中,开始分发数据
    // Handler有两个作用, (1) : 定时执行Message和Runnalbe 对象
    // (2): 让一个动作,在不同的线程中执行.

    Handler handler = new Handler() {// Handler对象用于更新当前步数,定时发送消息，调用方法查询数据用于显示？？？？？？？？？？
        //主要接受子线程发送的数据, 并用此数据配合主线程更新UI
        //Handler运行在主线程中(UI线程中), 它与子线程可以通过Message对象来传递数据,
        //Handler就承担着接受子线程传过来的(子线程用sendMessage()方法传递Message对象，(里面包含数据)
        //把这些消息放入主线程队列中，配合主线程进行更新UI。

        @Override                  //这个方法是从父类/接口 继承过来的，需要重写一次
        public void handleMessage(Message msg) {
            super.handleMessage(msg);        // 此处可以更新UI

            countDistance();     //调用距离方法，看一下走了多远

            countStep();          //调用步数方法

            tv_show_step.setText(total_step + "");// 显示当前步数

            tv_distance.setText(formatDouble(distance));// 显示路程

            tv_timer.setText(getFormatTime(timer));// 显示当前运行时间

        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.setContentView(R.layout.activity_run);  //设置当前屏幕

        if (RunSettingActivity.sharedPreferences == null) {
            RunSettingActivity.sharedPreferences = this.getSharedPreferences(
                    RunSettingActivity.SETP_SHARED_PREFERENCES,
                    Context.MODE_PRIVATE);
        }

        gifView = (GifView)findViewById(R.id.gif_view);
        gifView.setGifImageType(GifView.GifImageType.COVER);
        gifView.setShowDimension(300, 300);
        gifView.setGifImage(R.drawable.run_gif);
        gifView.showCover();

        if (thread == null) {

            thread = new Thread() {// 子线程用于监听当前步数的变化

                @Override
                public void run() {
                    super.run();
                    int temp = 0;
                    while (true) {
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (StepCounterService.FLAG) {
                            Message msg = new Message();
                            if (temp != StepDetector.CURRENT_SETP) {
                                temp = StepDetector.CURRENT_SETP;
                            }
                            if (startTimer != System.currentTimeMillis()) {
                                timer = tempTime + System.currentTimeMillis()
                                        - startTimer;
                            }
                            handler.sendMessage(msg);// 通知主线程
                        }
                    }
                }
            };
            thread.start();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        // 获取界面控件
        addView();

        // 初始化控件
        init();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 获取Activity相关控件
     */
    private void addView() {
        back = (ImageButton) this.findViewById(R.id.iv_left);
        tv_setting = (TextView) this.findViewById(R.id.tv_run_setting);

        tv_show_step = (TextView) this.findViewById(R.id.show_step);

        tv_timer = (TextView) this.findViewById(R.id.timer);

        tv_distance = (TextView) this.findViewById(R.id.distance);

        btn_start = (Button) this.findViewById(R.id.start);
        btn_stop = (Button) this.findViewById(R.id.stop);

        Intent service = new Intent(this, StepCounterService.class);
        stopService(service);
        StepDetector.CURRENT_SETP = 0;
        tempTime = timer = 0;
        tv_timer.setText(getFormatTime(timer));      //如果关闭之后，格式化时间
        tv_show_step.setText("0");
        tv_distance.setText(formatDouble(0.0));

        handler.removeCallbacks(thread);
    }

    /**
     * 初始化界面
     */
    private void init() {
        TextView title = (TextView) findViewById(R.id.tv_title);
        title.setText("跑步");
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tv_setting.setVisibility(View.VISIBLE);
        tv_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(RunActivity.this, RunSettingActivity.class);
                startActivity(intent);
            }
        });

        step_length = RunSettingActivity.sharedPreferences.getInt(
                RunSettingActivity.STEP_LENGTH_VALUE, 70);

        countDistance();
        countStep();

        tv_timer.setText(getFormatTime(timer + tempTime));

        tv_distance.setText(formatDouble(distance));

        tv_show_step.setText(total_step + "");

        btn_start.setEnabled(!StepCounterService.FLAG);
        btn_stop.setEnabled(StepCounterService.FLAG);

        if (StepCounterService.FLAG) {
            btn_stop.setText("暂停");
        } else if (StepDetector.CURRENT_SETP > 0) {
            btn_stop.setEnabled(true);
            btn_stop.setText("结束");
        }
    }

    /**
     * 计算并格式化doubles数值，保留两位有效数字
     *
     * @param doubles
     * @return 返回当前路程
     */
    private String formatDouble(Double doubles) {
        DecimalFormat format = new DecimalFormat("####.##");
        String distanceStr = format.format(doubles);
        return distanceStr.equals("0") ? "0.0" : distanceStr;
    }

    public void onClick(View view) {
        Intent service = new Intent(RunActivity.this, StepCounterService.class);
        switch (view.getId()) {
            case R.id.start:
                gifView.showAnimation();
                startService(service);
                btn_start.setEnabled(false);
                btn_stop.setEnabled(true);
                btn_stop.setText("暂停");
                startTimer = System.currentTimeMillis();
                tempTime = timer;
                break;

            case R.id.stop:
                stopService(service);
                gifView.showCover();
                if (StepCounterService.FLAG && StepDetector.CURRENT_SETP > 0) {
                    btn_stop.setText("结束");
                } else {
                    if (StepDetector.CURRENT_SETP > 0) {
                        // 提交数据
                        postSportData();
                    }

                    StepDetector.CURRENT_SETP = 0;
                    tempTime = timer = 0;

                    btn_stop.setText("暂停");
                    btn_stop.setEnabled(false);

                    tv_timer.setText(getFormatTime(timer));      //如果关闭之后，格式化时间

                    tv_show_step.setText("0");
                    tv_distance.setText(formatDouble(0.0));

                    handler.removeCallbacks(thread);
                }
                btn_start.setEnabled(true);
                break;
        }
    }

    /**
     * 得到一个格式化的时间
     *
     * @param time
     *            时间 毫秒
     * @return 时：分：秒：毫秒
     */
    private String getFormatTime(long time) {
        time = time / 1000;
        long second = time % 60;
        long minute = (time % 3600) / 60;
        long hour = time / 3600;

        // 毫秒秒显示两位
        // String strMillisecond = "" + (millisecond / 10);
        // 秒显示两位
        String strSecond = ("00" + second)
                .substring(("00" + second).length() - 2);
        // 分显示两位
        String strMinute = ("00" + minute)
                .substring(("00" + minute).length() - 2);
        // 时显示两位
        String strHour = ("00" + hour).substring(("00" + hour).length() - 2);

        return strHour + ":" + strMinute + ":" + strSecond;
        // + strMillisecond;
    }

    /**
     * 计算行走的距离                                                                        
     */
    private void countDistance() {
        if (StepDetector.CURRENT_SETP % 2 == 0) {
            distance = (StepDetector.CURRENT_SETP / 2) * 3 * step_length * 0.01;
        } else {
            distance = ((StepDetector.CURRENT_SETP / 2) * 3 + 1) * step_length * 0.01;
        }
    }

    /**
     * 实际的步数
     */
    private void countStep() {
        if (StepDetector.CURRENT_SETP % 2 == 0) {
            total_step = StepDetector.CURRENT_SETP;
        } else {
            total_step = StepDetector.CURRENT_SETP +1;
        }

        total_step = StepDetector.CURRENT_SETP;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    private void postSportData() {
        OkHttpUtils.post().url(API.UPLOAD_MILEAGE)
                .addParams("user_id", App.getLoginUser().id+"")
                .addParams("mileage", tv_distance.getText().toString())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }
            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if(jsonObject.getBoolean("state")) {
                        new AlertDialog.Builder(RunActivity.this)
                                .setMessage("本次跑步已结束")
                                .setPositiveButton("确认", null)
                                .show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
